// @algorithm @lc id=61 lang=cpp 
// @title rotate-list


// @test([1,2,3,4,5],2)=[4,5,1,2,3]
// @test([0,1,2],4)=[2,0,1]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return NULL;
        auto p = head, pre=p;
        int n = 0;
        while(p){
            pre = p;
            p = p->next;
            n++;
        }
        if(0==k%n) return head;
        pre->next = head;
        n -= k%n;
        while(n--){
            pre = head;
            head = head->next;
        }
        pre->next = NULL;
        return head;
    }
};